<template>
  <el-card shadow="hover">
  <el-input
    v-model="filterText"
    placeholder="过滤条件"
    prefix-icon="Search"
    clearable
  />
  <el-tree
    ref="treeRef"
    style="max-width: 600px"
    class="filter-tree"
    :data="data"
    :props="defaultProps"
    :expand-on-click-node="false"
    :filter-node-method="filterNode"
    default-expand-all
    highlight-current
    @node-click="nodeSelected"
  />
  </el-card>
</template>

<script lang="ts" setup>
import {defineEmits, defineProps, ref, watch} from 'vue'
import { ElTree } from 'element-plus'
import useDictStore from "@/store/modules/dict";
import {getDicts} from "@/api/system/dict/data";
import {TreeTT} from "@/api/demo/tree/types";

let filterText = ref('')
const treeRef = ref<InstanceType<typeof ElTree>>()
let data = ref<any>([])

const defaultProps = {
  children: 'children',
  label: 'dictLabel',
  id: 'dictCode'
}
const props = defineProps({
  dictType: { type: String, default: '' },
  dictValue: { type: String, default: '' },
  dictLabel: { type: String, default: '' },
});
watch(filterText, (val) => {
  treeRef.value!.filter(val) //显示数据过滤
})
const { proxy } = getCurrentInstance() as ComponentInternalInstance
function filterNode(value: string, Data: typeof data){
  if (!value) return true
  return Data.dictLabel.includes(value) //过滤数据
}


const emit = defineEmits(["update:dictValue"]);
/** 选择节点事件 */
function nodeSelected(data: TreeTT){
  emit('update:dictValue', data.dictValue) //为父组件中的v-model更新值
}

const routeDictType = String(props.dictType) //获取路由类型数据
async function getTreeList() {
  let res: any;
  const treeData = useDictStore().getDict(routeDictType)
  if (!treeData){
    res = await getDicts(routeDictType)
    res = res.data
    useDictStore().setDict(routeDictType,res)
  }else{
    res = toRaw(treeData)
  }
  data.value = proxy?.handleTree2<TreeTT>(res)
  // console.log(data.value)
}

onMounted(getTreeList)
</script>
